<!-- 数据库表列L新增、修改表单弹窗 -->
<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="displayModuleTitle"
    @ok="onButtonOkClick"
    width="1000px"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';

  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { dbTableColumnFormSchema } from './dbtablecolumn.data';
  import {
    addDBTableColumn,
    updateDBTableColumn,
    getDBTableColumn,
  } from '/@/api/platform/dbTableColumn';

  export default defineComponent({
    name: 'DBTableColumnEditForm',
    components: {
      BasicModal,
      BasicForm,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      /**
       * 组件之间传递数据的统一属性，包含模块名称、操作类型、数据ID
       */
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();

      /**
       * 显示的模块标题，用于显示在弹出框中的标题
       */
      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      const { createMessage } = useMessage();

      const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
        labelWidth: 120,
        schemas: dbTableColumnFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        //接收父组件传递的数据
        if (data != undefined && data != null) {
          qcUnifyProps.value = unref(data);
          console.log('接收的对象', data);
        }

        resetFields(); //重置表单
        setModalProps({ confirmLoading: false });

        // 设置表单选择项数据
        updateSchema({
          field: 'datatype',
          componentProps: {
            options: data.dataId.columnOptions.datatypeOptions,
          },
        });
        updateSchema({
          field: 'coltype',
          componentProps: {
            options: data.dataId.columnOptions.coltypeOptions,
          },
        });
        updateSchema({
          field: 'qccmptype',
          componentProps: {
            options: data.dataId.columnOptions.whereconditionOptions,
          },
        });

        updateSchema({
          field: 'tbcode',
          componentProps: { disabled: true },
        });

        // 如果是修改数据，根据传入的id获取数据后进行赋值
        if (data.operateType == OperationTypeEnum.EDIT) {
          getByCode();
          updateSchema({
            field: 'code',
            componentProps: { disabled: true },
          });
        } else {
          // 新增
          updateSchema({
            field: 'code',
            componentProps: { disabled: false },
          });
          let formData = {};
          if (data.dataId) {
            formData = {
              tbcode: data.dataId.tableCode,
            };
          }
          // 设置数据库表编码回显
          setFieldsValue({
            ...formData,
          });
        }
      });

      /**
       * 获取指定数据库信息
       */
      function getByCode() {
        getDBTableColumn(qcUnifyProps.value?.dataId.tableCode, qcUnifyProps.value?.dataId.code)
          .then((res) => {
            console.log('res', res);
            // 处理radio选项：编辑回显时不固定位置和不参与排序返回null，处理为“0”设置回显
            if (res.qrfixed == null || res.qrfixed == undefined || res.qrfixed == '') {
              res.qrfixed = '0';
            }
            if (res.qrascorder == null || res.qrascorder == undefined || res.qrascorder == '') {
              res.qrascorder = '0';
            }
            setFieldsValue({
              ...res,
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 点击确认按钮，根据不同的op调用对应方法保存信息
       */
      async function onButtonOkClick() {
        //对应操作的步骤为：验证表单、提交后台保存、关闭modal、调用父组件事件刷新数据
        const values = await validate();
        console.log('要提交表单数据values', values);
        setModalProps({ confirmLoading: true });

        if (qcUnifyProps.value?.operateType == OperationTypeEnum.ADD) {
          try {
            //调用接口进行保存
            addDBTableColumn(values)
              .then((res) => {
                if (!res || Object.keys(res).length == 0) {
                  createMessage.success('保存成功。', 2);
                }
                closeModal();
                emit('success');
              })
              .catch((ex) => {
                console.log('catch ', ex);
                createMessage.error(ex.msg);
              });
          } finally {
            setModalProps({ confirmLoading: false });
          }
        } else if (qcUnifyProps.value?.operateType == OperationTypeEnum.EDIT) {
          try {
            //调用接口进行保存
            updateDBTableColumn(values)
              .then((res) => {
                if (!res || Object.keys(res).length == 0) {
                  createMessage.success('修改成功。', 2);
                }
                closeModal();
                emit('success');
              })
              .catch((ex) => {
                console.log('catch ', ex);
                createMessage.error(ex.msg);
              });
          } finally {
            setModalProps({ confirmLoading: false });
          }
        } else {
          createMessage.error('当前操作类型错误，无法进行对应操作。', 5);
        }
      }

      return {
        registerModal,
        registerForm,
        displayModuleTitle,
        getByCode,
        onButtonOkClick,
      };
    },
  });
</script>
